package com.lemon.cloud.mp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lemon.cloud.comm.model.ResultMsg;
import com.lemon.cloud.mp.config.WxMpInitConfigService;
import com.lemon.cloud.mp.entity.WxAccount;
import com.lemon.cloud.mp.entity.WxMpMenu;
import com.lemon.cloud.mp.mapper.WxAccountMapper;
import com.lemon.cloud.mp.mapper.WxMpMenuMapper;
import com.lemon.cloud.mp.service.WxMenuService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class WxMpMenuServiceImpl extends ServiceImpl<WxMpMenuMapper, WxMpMenu> implements WxMenuService {

    @Autowired
    private WxAccountMapper wxAccountMapper;

    private static final String PUB_ED = "1";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(JSONObject wxMenus, String appId) {
        baseMapper.delete(Wrappers.<WxMpMenu>lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId));

        WxAccount wxAccount = wxAccountMapper
                .selectOne(Wrappers.<WxAccount>lambdaQuery().eq(WxAccount::getAppid, appId));
        WxMpMenu wxMpMenu = new WxMpMenu();
        wxMpMenu.setMenu(wxMenus.toJSONString());
        wxMpMenu.setWxAccountId(wxAccount.getId());
        wxMpMenu.setWxAccountAppid(wxAccount.getAppid());
        wxMpMenu.setWxAccountName(wxAccount.getName());
        baseMapper.insert(wxMpMenu);
        return Boolean.TRUE;
    }

    @Override
    public ResultMsg<Void> push(String appId) {
        List<WxMpMenu> wxMpMenuList = baseMapper
                .selectList(Wrappers.<WxMpMenu>lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId));

        if (CollectionUtil.isEmpty(wxMpMenuList)) {
            return ResultMsg.resultFail("微信菜单配置未保存，不能发布");
        }
        WxMpMenu wxMpMenu = wxMpMenuList.get(0);
        // 判断是否发布
        if (PUB_ED.equals(wxMpMenu.getPubFlag())) {
            return ResultMsg.resultFail("微信菜单配置已发布，不要重复发布");
        }
        WxMpService wxMpService = WxMpInitConfigService.getMpServices().get(appId);
        WxMpMenuService menuService = wxMpService.getMenuService();

        try {
            menuService.menuCreate(wxMpMenu.getMenu());
        }
        catch (WxErrorException e) {
            log.error("发布微信菜单失败,{}", e.getError().getErrorMsg());
            return ResultMsg.resultFail(e.getError().getErrorMsg());
        }

        // 更新菜单发布标志
        wxMpMenu.setPubFlag(PUB_ED);
        baseMapper.updateById(wxMpMenu);
        return ResultMsg.resultSuccess();
    }

    @Override
    public ResultMsg<String> getByAppId(String appId) {
        List<WxMpMenu> wxMpMenuList = baseMapper
                .selectList(Wrappers.<WxMpMenu>lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId));

        if (CollectionUtil.isEmpty(wxMpMenuList)) {
            return ResultMsg.resultSuccess();
        }
        return ResultMsg.resultSuccess(wxMpMenuList.get(0).getMenu());
    }

    @Override
    public ResultMsg<Void> delete(String appId) {
        WxMpService wxMpService = WxMpInitConfigService.getMpServices().get(appId);
        WxMpMenuService menuService = wxMpService.getMenuService();
        try {
            menuService.menuDelete();
        }
        catch (WxErrorException e) {
            log.error("微信菜单删除失败,{}", e.getError().getErrorMsg());
            return ResultMsg.resultFail(e.getError().getErrorMsg());
        }

        baseMapper.delete(Wrappers.<WxMpMenu>lambdaQuery().eq(WxMpMenu::getWxAccountAppid, appId));
        return ResultMsg.resultSuccess();
    }

    @Override
    public ResultMsg<String> syncMenu(String appId) {
        WxMpService wxMpService = WxMpInitConfigService.getMpServices().get(appId);
        WxMpMenuService menuService = wxMpService.getMenuService();
        try {
            me.chanjar.weixin.mp.bean.menu.WxMpMenu wxMpMenu = menuService.menuGet();
            return ResultMsg.resultSuccess(wxMpMenu.getMenu().toString());
        }
        catch (WxErrorException e) {
            log.error("微信菜单获取失败,{}", e.getError().getErrorMsg());
            return ResultMsg.resultFail("微信菜单获取失败:"+e.getError().getErrorMsg());
        }
    }
}
